import { SuccessModel, ErrorModel } from '@utils/respond/ResModel';
import { Roles, Menus } from '../models';
/**
 * 分页获取角色列表
 */
export const getRolePage = async({ page = 1, size = 20 }) => {
    const result = await Roles.findAndCountAll({
        limit: size,
        offset: (page - 1) * size
    });
    return new SuccessModel({ data: result })
}

/**
 * 获取所有角色
 */
export const getRoleList = async() => {
    const result = await Roles.findAll();
    return new SuccessModel({ data: result })
}

/**
 * 格式化menuId
 * 如果用户只传了某个按钮权限，需要把按钮对应的上级也要加上
 * 比如 菜单id为1，下面又children 2 3 4，用户只传了2，要把1也加上
 * 不存在用户传了1，没有传2,3,4的情况，所以只需要判断权限即可。
 */
async function formatMenuId(menuIds) {
    const allMenus = await Menus.findAll();
    let ids = [];

    function getParentMenu(id) {
        const menu = allMenus.find(menu => menu.id === id);
        menu && ids.push(menu.id);
        if (menu && menu.parentId) {
            getParentMenu(menu.parentId);
        }
    }
    menuIds.forEach(key => {
        const menu = allMenus.find(menu => menu.id === key);
        ids.push(menu.id);
        getParentMenu(menu.parentId);
    })
    return ids;
}

/**
 * 添加角色
 */
export const addRole = async(body) => {
    const { label, describe, menuIds, status } = body;
    const ids = await formatMenuId(menuIds);
    const role = await Roles.create({
        label,
        describe,
        status
    });
    if (ids.length > 0) {
        let menus = await Menus.findAll({ where: { id: ids } });
        role.setMenus(menus)
    }
    return new SuccessModel({ data: role })
}

/**
 * 角色详情
 */
export const getRoleDetail = async(roleId) => {
    try {
        const role = await Roles.findOne({
            where: { id: roleId },
            include: [{
                model: Menus,
                through: {
                    attributes: []
                }
            }]
        })
        return new SuccessModel({ data: role })
    } catch (error) {
        console.log('error', error);
        return new ErrorModel({ msg: '获取错误' })
    }
}

/**
 * 更新角色
 */
export const updateRole = async(body) => {
    try {
        const { id, label, describe, status, menuIds } = body;
        const ids = await formatMenuId(menuIds);
        let updateResult = await Roles.update({ label, describe, status }, {
            where: { id }
        });
        // mysql不支持更新后返回更新内容
        if (updateResult && updateResult.length > 0) {
            const role = await Roles.findOne({ where: { id } });
            if (menuIds && menuIds.length > 0) {
                let menus = await Menus.findAll({ where: { id: ids } });
                role.setMenus(menus)
            }
            return new SuccessModel({ role })
        }
        return new ErrorModel({ message: "更新失败" })

    } catch (error) {
        console.log('error', error);
        return new ErrorModel({ message: error })
    }
}

/**
 * 删除角色
 */
export const deleteRole = async(body) => {

}